package com.wiselink.coupang.productcatalog;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.wiselink.coupang.CoupangBaseAPI;
import com.wiselink.coupang.productcatalog.ado.PlatformProductADO;
import com.wiselink.exception.CoupangException;
import com.wiselink.coupang.productcatalog.request.PlatformProduct;
import com.wiselink.coupang.productcatalog.request.PlatformProductRequestParam;
import com.wiselink.coupang.productcatalog.response.ShopAuthorizeResponse;
import com.wiselink.coupang.productcatalog.response.displayCategories.DisplayCategoriesResponse;
import com.wiselink.coupang.productcatalog.response.queryCategoryRelatedMetas.QueryCategoryRelatedMetasResponse;
import com.wiselink.coupang.productcatalog.response.returnShippingCenters.ReturnShippingCentersResponse;
import com.wiselink.coupang.productcatalog.response.returnShippingCenters.ReturnShippingCentersVo;
import com.wiselink.coupang.productcatalog.response.shippingPlaceOutbound.ShippingPlaceOutboundResponse;
import com.wiselink.coupang.productcatalog.response.shippingPlaceOutbound.ShippingPlaceOutboundVo;
import com.wiselink.coupang.ShopVO;
import org.springframework.beans.BeanUtils;

import java.text.SimpleDateFormat;
import java.util.Objects;

/**
 * coupang-商品相关接口调用工具类
 */
public class APIUtils extends CoupangBaseAPI {
    // 店铺授权
    private static final String PATH_DO_AUTHORIZATION = "/v2/providers/openapi/apis/api/v4/vendors/{vendorId}/{orderId}/ordersheets";
    // 商品注册
    private static final String PATH_PRODUCT_REGISTER = "/v2/providers/seller_api/apis/api/v1/marketplace/seller-products";
    // 商品修改
    private static final String PATH_PRODUCT_MODIFY = "/v2/providers/seller_api/apis/api/v1/marketplace/seller-products";
    // 商品删除
    private static final String PATH_PRODUCT_DELETE = "/v2/providers/seller_api/apis/api/v1/marketplace/seller-products/{sellerProductId}";
    // 商品审核申请
    private static final String PATH_PRODUCT_APPROVALS = "/v2/providers/seller_api/apis/api/v1/marketplace/seller-products/{sellerProductId}/approvals";
    // 商品查询
    private static final String PATH_PRODUCT_QUERY = "/v2/providers/seller_api/apis/api/v1/marketplace/seller-products/{sellerProductId}";
    // 商品列表分页查询
    private static final String PATH_PRODUCT_LIST = "/v2/providers/seller_api/apis/api/v1/marketplace/seller-products";
    // 退货地列表查询
    private static final String PATH_RETURN_SHIPPING_CENTERS = "/v2/providers/openapi/apis/api/v4/vendors/{vendorId}/returnShippingCenters";
    // 发货地查询
    private static final String PATH_SHIPPING_PLACE_OUTBOUND = "/v2/providers/marketplace_openapi/apis/api/v1/vendor/shipping-place/outbound";
    // 查询品类列表
    private static final String PATH_DISPLAY_CATEGORIES = "/v2/providers/seller_api/apis/api/v1/marketplace/meta/display-categories";
    // 查看品类
    private static final String PATH_DISPLAY_CATEGORIES_SHOW = "/v2/providers/seller_api/apis/api/v1/marketplace/meta/display-categories/{displayCategoryCode}";
    // 品类元数据查询
    private static final String PATH_QUERY_CATEGORY_RELATED_METAS = "/v2/providers/seller_api/apis/api/v1/marketplace/meta/category-related-metas/display-category-codes/{displayCategoryCode}";

    /**
     * 店铺授权
     *
     * @param vo vo
     * @return ShopAuthorizeResponse
     */
    public static ShopAuthorizeResponse doAuthorization(ShopVO vo) {
        String path = PATH_DO_AUTHORIZATION;
        // 替换自己的vendorId
        path = path.replace("{vendorId}", vo.getShopId()).replace("{orderId}", "12345678");
        // 生成鉴权字符串
        String authorization = generateHMACSignature(Method.GET.name(), path, vo);
        log.debug(authorization);
        String result = executeRequest(authorization, path, null, "doAuthorization", Method.GET);
        log.error("店铺授权-result: {}", result);
        return JSONObject.parseObject( result, ShopAuthorizeResponse.class);
    }

    /**
     * 商品注册
     *
     * @param ado ado
     * @param vo  vo
     * @return 注册成功后的商品ID
     */
    public static String productRegister(PlatformProductADO ado, ShopVO vo) {
        PlatformProductRequestParam requestParam = new PlatformProductRequestParam();
        BeanUtils.copyProperties(ado, requestParam);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        requestParam.setSaleStartedAt(sdf.format(ado.getSaleStartedAt()));
        requestParam.setSaleEndedAt(sdf.format(ado.getSaleEndedAt()));
        requestParam.setOutboundShippingPlaceCode(Long.valueOf(ado.getOutboundShippingPlaceCode()));
        // 生成鉴权字符串
        String authorization = generateHMACSignature(Method.POST.name(), PATH_PRODUCT_REGISTER, vo);

        String result = executeRequest(authorization, PATH_PRODUCT_REGISTER, JSON.toJSONString(requestParam), "productRegister", Method.POST);
        String sellerProductId;
        /*
            {"code":"SUCCESS","message":"[1617 카테고리는 null 옵션의 사용을 추천하지 않습니다. 입력하신 추가 옵션은 검수 후 노출됩니다.]","data":15171511499,"details":null,"errorItems":null}
         */
        JSONObject jsonObject = JSON.parseObject(result);
        String code = jsonObject.get("code") != null ? jsonObject.get("code").toString() : "";
        if ("SUCCESS".equals(code)) {
            sellerProductId = jsonObject.get("data").toString();
        } else {
            log.error("平台商品注册失败：{}", jsonObject);
            throw new CoupangException("平台商品注册失败,原因：" + jsonObject);
        }
        if (sellerProductId == null) {
            log.error("平台商品注册失败：sellerProductId is null");
            throw new CoupangException("平台商品注册失败,sellerProductId is null");
        }
        return sellerProductId;
    }

    /**
     * 商品修改
     *
     * @param ado ado
     * @param vo  vo
     */
    public static void productModify(PlatformProduct ado, ShopVO vo) {
        // 生成鉴权字符串
        String authorization = generateHMACSignature(Method.PUT.name(), PATH_PRODUCT_MODIFY, vo);
        String result = executeRequest(authorization, PATH_PRODUCT_MODIFY, JSON.toJSONString(ado), "productModify", Method.PUT);
        /*
             {
             "code": "200",
             "message": "",
             "data": {
                 "code": "SUCCESS",
                 "message": "",
                 "data": 7770
                 }
             }
         */
        JSONObject jsonObject = JSON.parseObject(result);
        String code = jsonObject.get("code") != null ? jsonObject.get("code").toString() : "";
        if ("200".equals(code)) {
            JSONObject data = jsonObject.getJSONObject("data");
            boolean hasData = data != null;

            String dataCode = hasData ? data.get("code") != null ? data.get("code").toString() : "" : "";
            if (!"SUCCESS".equals(dataCode)) {
                String failMsg = "平台商品修改失败,原因：";
                if (hasData) {
                    if (data.get("message") != null) {
                        failMsg += data.get("message").toString();
                    }
                }
                throw new CoupangException(failMsg);
            }
        }
        throw new CoupangException("平台商品修改失败,reason:" + result);
    }

    /**
     * 商品删除
     *
     * @param sellerProductId sellerProductId
     * @param vo              vo
     */
    public static void productDelete(String sellerProductId, ShopVO vo) {
        String path = PATH_PRODUCT_DELETE;
        path = path.replace("{sellerProductId}", sellerProductId);
        String authorization = generateHMACSignature(Method.DELETE.name(), path, vo);
        String result = executeRequest(authorization, path, null, "productDelete", Method.DELETE);
        /*
             {
             "code": "SUCCESS",
             "message": "삭제되었습니다",
             "data": "10***16568"
             }
         */
        JSONObject jsonObject = JSON.parseObject(result);
        String code = jsonObject.get("code") != null ? jsonObject.get("code").toString() : "";
        if (!"SUCCESS".equals(code)) {
            throw new CoupangException("平台商品 " + sellerProductId + " 删除失败,reason:" + jsonObject.get("message"));
        }
    }

    /**
     * 商品审核申请
     *
     * @param sellerProductId sellerProductId
     * @param vo              vo
     */
    public static void productApprovals(String sellerProductId, ShopVO vo) {
        String path = PATH_PRODUCT_APPROVALS;
        path = path.replace("{sellerProductId}", sellerProductId);
        String authorization = generateHMACSignature(Method.PUT.name(), path, vo);
        String result = executeRequest(authorization, path, "", "productApprovals", Method.PUT);
         /*
             {
             "code": "SUCCESS",
             "message": "A request for approving 1320***567"went out.It an issue if found with the product, it may not be approved.",
             "data": "1320***567"
             }
         */
        JSONObject jsonObject = JSON.parseObject(result);
        String code = jsonObject.get("code") != null ? jsonObject.get("code").toString() : "";
        if (!"SUCCESS".equals(code)) {
            throw new CoupangException("平台商品 " + sellerProductId + " 审核申请失败,reason:" + jsonObject.get("message"));
        }
    }

    /**
     * 商品查询
     *
     * @param sellerProductId sellerProductId
     * @param vo              vo
     * @return 产品详情
     */
    public static String productQuery(String sellerProductId, ShopVO vo) {
        String path = PATH_PRODUCT_QUERY;
        path = path.replace("{sellerProductId}", sellerProductId);
        String authorization = generateHMACSignature(Method.GET.name(), path, vo);
        String result = executeRequest(authorization, path, null, "productApprovals", Method.GET);
        // TODO 待解析产品详情
        log.debug("查询结果：{}", result);
        return result;
    }

    /**
     * 商品列表分页查询
     *
     * @param ado ado
     * @param vo  vo
     * @return String
     */
    public static String productQueryList(PlatformProduct ado, ShopVO vo) {
        String path = PATH_PRODUCT_LIST;
        StringBuilder qs = new StringBuilder();
        qs.append("?").append("vendorId=").append(ado.getVendorId());// 卖家ID 酷澎分配给卖家的固有代码
        qs.append("&").append("nextToken=");// 页面 调用下一页的关键值  调用第一页时，不要输入或输入'1'
        if (Objects.isNull(ado.getNextToken())) {
            qs.append("1");
        } else {
            qs.append(ado.getNextToken());
        }
        qs.append("&").append("maxPerPage=");// 每页件数 默认值：10；最大值: 100
        if (Objects.isNull(ado.getMaxPerPage())) {
            qs.append("10");
        } else {
            qs.append(ado.getMaxPerPage());
        }
        if (Objects.nonNull(ado.getSellerProductId())) {
            qs.append("&").append("sellerProductId=").append(ado.getSellerProductId());
        }
        if (Objects.nonNull(ado.getSellerProductName())) {
            qs.append("&").append("sellerProductName=").append(ado.getSellerProductName());// 注册商品名 搜索注册商品名，20字以内
        }
        if (Objects.nonNull(ado.getStatusName())) {
            qs.append("&").append("status=").append(ado.getStatusName());// 卖家商品状态
        }
        if (Objects.nonNull(ado.getManufacture())) {
            qs.append("&").append("manufacture=").append(ado.getManufacture());// 制造商
        }
        if (Objects.nonNull(ado.getSaleStartedAt())) {
            qs.append("&").append("createdAt=").append(new SimpleDateFormat("yyyy-MM-dd").format(ado.getSaleStartedAt()));// 商品注册时间 格式"yyyy-MM-dd"
        }
        path += qs;
        String authorization = generateHMACSignature(Method.GET.name(), path, vo);
        String result = executeRequest(authorization, path, null, "productQueryList", Method.GET);
        // TODO 待解析产品列表详情
        log.debug("商品列表分页查询结果：{}", result);
        return result;
    }

    /**
     * 退货地列表查询
     *
     * @param ado ado
     * @param vo  vo
     * @return ReturnShippingCentersResponse
     */
    public static ReturnShippingCentersResponse returnShippingCenters(ReturnShippingCentersVo ado, ShopVO vo) {
        String path = PATH_RETURN_SHIPPING_CENTERS;
        path = path.replace("{vendorId}", vo.getShopId());
        String authorization = generateHMACSignature(Method.GET.name(), path, vo);
        String result = executeRequest(authorization, path, null, "returnShippingCenters", Method.GET);
        return JSONObject.parseObject( result, ReturnShippingCentersResponse.class);
    }

    /**
     * 发货地查询
     *
     * @param ado ado
     * @param vo  vo
     * @return ShippingPlaceOutboundResponse
     */
    public static ShippingPlaceOutboundResponse shippingPlaceOutbound(ShippingPlaceOutboundVo ado, ShopVO vo) {
        String path = PATH_SHIPPING_PLACE_OUTBOUND;
        StringBuilder qs = new StringBuilder();
        qs.append("?").append("pageNum=").append(ado.getPageNum());
        qs.append("&").append("pageSize=").append(ado.getPageSize());
        if (Objects.nonNull(ado.getOutboundShippingPlaceCode())) {
            qs.append("&").append("placeCodes=").append(ado.getOutboundShippingPlaceCode());
        }
        if (Objects.nonNull(ado.getShippingPlaceName())) {
            qs.append("&").append("placeNames=").append(ado.getShippingPlaceName());
        }
        path += qs;
        String authorization = generateHMACSignature(Method.GET.name(), path, vo);
        String result = executeRequest(authorization, path, null, "shippingPlaceOutbound", Method.GET);
        return JSONObject.parseObject(result, ShippingPlaceOutboundResponse.class);
    }

    /**
     * 查询品类列表
     *
     * @param vo vo
     * @return DisplayCategoriesResponse
     */
    public static DisplayCategoriesResponse displayCategories(ShopVO vo) {
        String authorization = generateHMACSignature(Method.GET.name(), PATH_DISPLAY_CATEGORIES, vo);
        String result = executeRequest(authorization, PATH_DISPLAY_CATEGORIES, null, "displayCategories", Method.GET);
        return JSONObject.parseObject(result, DisplayCategoriesResponse.class);
    }

    /**
     * 查看品类
     *
     * @param displayCategoryCode displayCategoryCode
     * @param vo                  vo
     * @return DisplayCategoriesResponse
     */
    public static DisplayCategoriesResponse displayCategoriesShow(String displayCategoryCode, ShopVO vo) {
        String path = PATH_DISPLAY_CATEGORIES_SHOW;
        path = path.replace("{displayCategoryCode}", displayCategoryCode);
        String authorization = generateHMACSignature(Method.GET.name(), path, vo);
        String result = executeRequest(authorization, path, null, "displayCategoriesShow", Method.GET);
        return JSONObject.parseObject(result, DisplayCategoriesResponse.class);
    }

    /**
     * 品类元数据查询
     *
     * @param displayCategoryCode displayCategoryCode
     * @param vo                  vo
     * @return QueryCategoryRelatedMetasResponse
     */
    public static QueryCategoryRelatedMetasResponse queryCategoryRelatedMetas(String displayCategoryCode, ShopVO vo) {
        String path = PATH_QUERY_CATEGORY_RELATED_METAS;
        path = path.replace("{displayCategoryCode}", displayCategoryCode);
        String authorization = generateHMACSignature(Method.GET.name(), path, vo);
        String result = executeRequest(authorization, path, null, "queryCategoryRelatedMetas", Method.GET);
        return JSONObject.parseObject(result, QueryCategoryRelatedMetasResponse.class);
    }
}
